from datetime import date
import hashlib
import requests
import time
import random
import argparse

auth_token = '2anTxKWj2rPDcEqbiux0iMQ185PgcbNGjNa7664m1N4Tsxm3hswcVFXjNZZ90C4gC9uN89'

company_pos = {"long": {"fix": 104, "range": [103264, 103955]}, "lati": {"fix":30, "range":[521484, 522215]}}
user_id = '20000239819'

def is_holiday(Date:date =date.today()):
    url = "https://api.apihubs.cn/holiday/get?field=workday&date=20220403,20220402&cn=1&size=31"
    data= {"cn":1, "size":31, "field":"workday", "date":[Date.strftime("%Y%m%d")]}
    response = requests.get(url, params=data, timeout=3)
    if not response.ok:
        return False
    result = response.json()["data"]["list"][0]
    return result["workday"] == 2


def get_headers():
    headers = {
        'X-Hotchat-Auth-Token': auth_token,
        'X-Device': '16s',
        'X-Client': 'android',
        'X-Sign': '',
        'X-Version': '2092000',
        'X-Verify': '',
        'Accept-Language': 'zh-CN',
        'X-Ts': f'{int(time.time_ns()/1e6)}',
        'Connection': 'Keep-Alive',
        'User-Agent': 'okhttp/3.12.0',
        'Content-Type': 'application/json; charset=utf-8',
    }
    return headers


def get_token():
    headers = get_headers()
    response = requests.get(
        'https://hotchat-punch.iqiyi.com/rest/biz/punch/public/v3/token', headers=headers)
    if not response.ok:
        raise Exception("get token failed") 
    if response.json()['code'] != "A00000":
        print(response.json())
        raise Exception("get token failed") 
    token = response.json()['data']
    return token

def make_shake_sign(token, longtitude, latitude):
    md5 = hashlib.md5()    
    md5.update(f'{token}{user_id}{longtitude}{latitude}'.encode('utf-8'))
    return md5.hexdigest()

def randomPos(pos):
    rng = pos["range"]
    rpos = f'{pos["fix"]}.{random.randint(rng[0], rng[1])}'
    return rpos

def shake(token):
    headers = get_headers()
    longtitude = randomPos(company_pos["long"])
    latitude = randomPos(company_pos["lati"])
    print(longtitude, latitude)
    data = {"longitude": longtitude, "latitude": latitude, "token":token, 
        "qyid":"74aeb9e2a6b97777bcb3913240d04f7b110d","sign":make_shake_sign(token, longtitude, latitude),
        "root":False,"bssid":"80:8d:b7:cb:04:71","ssid":"qiyi-private-pki(2.4G)","vpn":False}

    response = requests.post(
        'https://hotchat-punch.iqiyi.com/rest/biz/punch/public/v3/shake', headers=headers, json=data)
    if not response.ok:
        raise Exception("http failed: code={} data={}".format(response.status_code, data)) 
    return response.json()

def shake_work(force:bool):
    try:
        random.seed()
        if not force and is_holiday():
            return "it's holiday!!!"
        token = get_token()
        return shake(token)
    except Exception as e:
        return "oh no! failed:{}".format(e)

if __name__ == "__main__":
    parser = argparse.ArgumentParser() 
    parser.add_argument("--force", help="force shake", type=bool, default=False)
    args = parser.parse_args()
    result = shake_work(args.force)
    print(result)
